<template>
  <div class="my-follows">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">我的关注</h1>
      <p class="page-description">查看你关注的所有角色</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 角色卡片网格 -->
    <div v-else class="character-grid">
      <!-- 关注的角色卡片 -->
      <el-card 
        v-for="character in followedCharacters" 
        :key="character.id" 
        class="character-card" 
        shadow="hover"
        @click="showCharacterDetail(character.id)"
      >
        <div class="character-avatar">
          <el-avatar 
            :size="80" 
            :src="character.image" 
            :icon="User"
          />
        </div>
        <div class="character-info">
          <h3 class="character-name">{{ character.name }}</h3>
          <p class="character-desc">{{ character.appearance }}</p>
        </div>
      </el-card>

      <!-- 空状态 -->
      <div v-if="followedCharacters && followedCharacters.length === 0" class="empty-state">
        <el-empty description="你还没有关注任何角色，快去角色广场看看吧！">
          <el-button type="primary" @click="$router.push('/app/character-square')">
            去角色广场
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 角色详情模态窗口 -->
    <el-dialog
      v-model="showDetailDialog"
      title="角色详情"
      width="700px"
      :before-close="() => showDetailDialog = false"
      class="character-detail-dialog"
    >
      <div v-if="detailLoading" class="detail-loading">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else-if="selectedCharacter" class="character-detail">
        <div class="detail-header">
          <div class="detail-avatar">
            <el-avatar 
              :size="120" 
              :src="selectedCharacter.image" 
              :icon="User"
            />
          </div>
          <div class="detail-info">
            <h2 class="detail-name">{{ selectedCharacter.name }}</h2>
            <p class="detail-appearance">{{ selectedCharacter.appearance }}</p>
          </div>
        </div>
        
        <div class="detail-content">
          <div class="detail-section">
            <h3 class="section-title">背景故事</h3>
            <p class="section-content">{{ selectedCharacter.background }}</p>
          </div>
          
          <div class="detail-section">
            <h3 class="section-title">性格特点</h3>
            <p class="section-content">{{ selectedCharacter.personality }}</p>
          </div>
          
          <div class="detail-section">
            <h3 class="section-title">经典台词</h3>
            <p class="section-content">{{ selectedCharacter.classicLines }}</p>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="startChat">开始对话</el-button>
          <el-button 
            v-if="followStatus" 
            type="danger" 
            :loading="followLoading"
            @click="handleUnfollow"
          >
            取消关注
          </el-button>
          <el-button 
            v-else 
            type="primary" 
            :loading="followLoading"
            @click="handleFollow"
          >
            关注
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'
import { characterApi, type Character } from '../api/character'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const followedCharacters = ref<Character[]>([])
const loading = ref(false)
const unfollowLoading = ref<number | null>(null)

// 角色详情相关
const showDetailDialog = ref(false)
const detailLoading = ref(false)
const selectedCharacter = ref<Character | null>(null)
const charactersCache = new Map<string, Character>()

// 关注状态相关
const followStatus = ref<boolean>(false)
const followLoading = ref(false)

// 获取关注列表
const fetchFollowedCharacters = async () => {
  try {
    loading.value = true
    const response = await characterApi.getFollowList()
    if (response.code === 1) {
      followedCharacters.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取关注列表失败')
    }
  } catch (error) {
    console.error('获取关注列表失败:', error)
    ElMessage.error('获取关注列表失败')
  } finally {
    loading.value = false
  }
}

// 显示角色详情
const showCharacterDetail = async (characterId: number) => {
  try {
    showDetailDialog.value = true
    
    // 检查缓存
    if (charactersCache.has(characterId.toString())) {
      selectedCharacter.value = charactersCache.get(characterId.toString())!
      // 获取关注状态
      await checkFollowStatus(characterId)
      return
    }
    
    detailLoading.value = true
    const response = await characterApi.getDetail(characterId)
    // 根据API返回格式：{code, msg, data: Character}
    selectedCharacter.value = response.data
    
    // 缓存角色详情
    if (response.data) {
      charactersCache.set(characterId.toString(), response.data)
    }
    
    // 获取关注状态
    await checkFollowStatus(characterId)
  } catch (error: any) {
    console.error('获取角色详情失败:', error)
    ElMessage.error('获取角色详情失败，请重试')
    showDetailDialog.value = false
  } finally {
    detailLoading.value = false
  }
}

// 检查关注状态
const checkFollowStatus = async (characterId: number) => {
  try {
    const response = await characterApi.getFollowStatus(characterId)
    if (response.code === 1) {
      followStatus.value = response.data
    }
  } catch (error: any) {
    console.error('获取关注状态失败:', error)
    // 不显示错误消息，静默处理
    followStatus.value = false
  }
}

// 关注角色
const handleFollow = async () => {
  if (!selectedCharacter.value) return
  
  try {
    followLoading.value = true
    const response = await characterApi.followCharacter(selectedCharacter.value.id)
    if (response.code === 1) {
      followStatus.value = true
      ElMessage.success('关注成功！')
    } else {
      throw new Error(response.msg || '关注失败')
    }
  } catch (error: any) {
    console.error('关注失败:', error)
    ElMessage.error(error.message || '关注失败，请重试')
  } finally {
    followLoading.value = false
  }
}

// 取消关注
const handleUnfollow = async () => {
  if (!selectedCharacter.value) return
  
  try {
    followLoading.value = true
    const response = await characterApi.unfollowCharacter(selectedCharacter.value.id)
    if (response.code === 1) {
      followStatus.value = false
      ElMessage.success('已取消关注')
      // 从列表中移除该角色
      followedCharacters.value = followedCharacters.value.filter(char => char.id !== selectedCharacter.value!.id)
      // 关闭详情窗口
      showDetailDialog.value = false
    } else {
      throw new Error(response.msg || '取消关注失败')
    }
  } catch (error: any) {
    console.error('取消关注失败:', error)
    ElMessage.error(error.message || '取消关注失败，请重试')
  } finally {
    followLoading.value = false
  }
}

// 开始对话
const startChat = () => {
  if (selectedCharacter.value) {
    const id = selectedCharacter.value.id as number
    const memoryId = `char-${id}`
    showDetailDialog.value = false
    router.push({
      name: 'Chat',
      params: { id: String(id) },
      query: { memoryId }
    })
  }
}

// 页面加载时获取关注列表
onMounted(() => {
  fetchFollowedCharacters()
})
</script>

<style scoped>
.my-follows {
  padding: 20px;
  background-color: #fdf2f8;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-title {
  font-size: 32px;
  font-weight: bold;
  color: #ec4899;
  margin: 0 0 10px 0;
}

.page-description {
  font-size: 16px;
  color: #be185d;
  margin: 0;
}

.loading-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.character-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.character-card {
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid #f9a8d4;
  position: relative;
  overflow: hidden;
}

.character-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(236, 72, 153, 0.1), transparent);
  transition: left 0.5s;
}

.character-card:hover {
  transform: translateY(-8px) scale(1.02);
  box-shadow: 0 12px 35px rgba(236, 72, 153, 0.2);
  border-color: #ec4899;
}

.character-card:hover::before {
  left: 100%;
}

.character-card:active {
  transform: translateY(-4px) scale(1.01);
  transition: all 0.1s ease;
}

.character-avatar {
  text-align: center;
  margin-bottom: 15px;
}

.character-info {
  text-align: center;
  margin-bottom: 15px;
}

.character-name {
  font-size: 18px;
  font-weight: 600;
  color: #ec4899;
  margin: 0 0 8px 0;
}

.character-desc {
  font-size: 14px;
  color: #be185d;
  margin: 0;
  line-height: 1.4;
}

.character-actions {
  text-align: center;
  padding-top: 10px;
  border-top: 1px solid #f3e8ff;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
}

/* 角色详情样式 */
.detail-loading {
  padding: 20px;
}

.character-detail {
  padding: 20px;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f3e8ff;
}

.detail-info {
  margin-left: 20px;
  flex: 1;
}

.detail-info h2 {
  font-size: 1.8rem;
  color: #be185d;
  margin: 0 0 10px 0;
}

.detail-appearance {
  color: #6b7280;
  font-size: 1rem;
  margin: 0;
  line-height: 1.5;
}

.detail-content {
  space-y: 20px;
}

.detail-section {
  margin-bottom: 25px;
}

.detail-section h3 {
  font-size: 1.2rem;
  color: #be185d;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.detail-section p {
  color: #374151;
  line-height: 1.6;
  margin: 0;
  white-space: pre-wrap;
}

/* 角色详情弹窗样式 */
.character-detail-dialog .el-dialog__body {
  padding: 20px;
}

.character-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-avatar {
  margin-right: 20px;
  flex-shrink: 0;
}

.detail-info {
  flex: 1;
}

.detail-name {
  font-size: 24px;
  font-weight: bold;
  color: #ec4899;
  margin: 0 0 10px 0;
}

.detail-appearance {
  font-size: 16px;
  color: #be185d;
  margin: 0;
  line-height: 1.5;
}

.detail-content {
  space-y: 20px;
}

.detail-section {
  margin-bottom: 25px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #ec4899;
  margin: 0 0 10px 0;
  padding-bottom: 5px;
  border-bottom: 2px solid #f9a8d4;
}

.section-content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin: 0;
  padding: 10px 0;
}

.detail-loading {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-follows {
    padding: 15px;
  }
  
  .page-title {
    font-size: 2rem;
  }
  
  .character-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .detail-header {
    flex-direction: column;
    text-align: center;
  }
  
  .detail-info {
    margin-left: 0;
    margin-top: 15px;
  }
}
</style>